<template>
    <el-dialog class="common-dialog" v-model="dialogVisible" title="账号信息" width="40%" @closed="handleDialogClosed">

        <div class="detail">

            <div class="detail-box">

                <el-form class="common-form-inline" label-position="top" label-width="100px" :model="form"
                    :rules="rules" ref="addFormRef" :validate-on-rule-change="false">

                    <el-form-item label="用户账号" prop="UserAccount">
                        <el-input class="common-input" v-model="form.UserAccount" maxlength="8" placeholder="请填写用户账号"
                            :disabled="!!form.userId"></el-input>
                    </el-form-item>

                    <el-form-item label="用户名" prop="UserName">
                        <el-input class="common-input" v-model="form.UserName" maxlength="20"
                            placeholder="请填写用户名"></el-input>
                    </el-form-item>


                    <!-- 管理角色切换按钮 -->
                    <el-form-item class="common-radio" label="管理角色" prop="UserRoleType">

                        <el-radio-group @change="handleRoleChange" v-model="form.UserRoleType">
                            <el-radio v-if="UserRole" :value="1">超级管理员</el-radio>
                            <el-radio v-if="form.UserAccount !== 'SYSADMIN'" :value="2">分级管理员</el-radio>
                        </el-radio-group>

                    </el-form-item>


                    <!-- 下拉框地区码选择 -->
                    <el-form-item label="权限组" prop="AccessGroupId" required v-if="form.UserRoleType !== 1">
                        <el-tree-select v-model="form.AccessGroupId" :data="treeData" :props="{
                            value: 'value',
                            label: 'label',
                            children: 'children'
                        }" check-strictly @node-click="handleNodeClick" style="width: 100%" placeholder="请选择权限组" />
                    </el-form-item>


                    <el-form-item label="联系电话" prop="PhoneNo">
                        <el-input v-model="form.PhoneNo" placeholder="请输入联系电话" class="common-input">
                            <template #prepend>
                                <el-select class="common-select money-select" v-model="form.AreaCode" fit-input-width>
                                    <el-option v-for="item in getCountryCodeList()" :key="item.areaCode"
                                        :label="`+${item.areaCode}`" :value="item.areaCode"></el-option>
                                </el-select>
                            </template>
                        </el-input>
                    </el-form-item>


                    <!-- 邮箱地址 -->
                    <el-form-item label="邮箱地址" prop="Email">
                        <el-input class="common-input" v-model="form.Email" placeholder="请输入邮箱地址"
                            maxlength="64"></el-input>
                    </el-form-item>

                    <!-- TFA二次验证选择按钮 -->
                    <el-form-item label="是否二次验证" prop="RequireTFA">
                        <el-radio-group class="common-radio" v-model="form.RequireTFA">
                            <el-radio :value="false">否</el-radio>
                            <el-radio :value="true">是</el-radio>
                        </el-radio-group>
                    </el-form-item>

                </el-form>

                <div class="common-group-button editBottom">
                    <el-button style="background: #2258F6; color: #fff;" :loading="loading" @click="save">确认</el-button>
                    <el-button class="cancel-button" @click="goReturn">返回</el-button>
                </div>

            </div>

            <!-- 二次验证弹框区域 -->
            <!--禁用-->
            <NormalDialog :visible="disableAccountVisible" @close="closeDisableDialog" title="封禁账号" content="确认要封禁账号吗"
                :confirm-method="disableAccount" :icon="iconWarning"></NormalDialog>
            <!--启用-->
            <NormalDialog :visible="enableAccountVisible" @close="closeDisableDialog" title="启用账号" content="确认要启用账号吗"
                :confirm-method="enableAccount" :icon="iconWarning"></NormalDialog>

        </div>

    </el-dialog>
</template>

<script setup lang="ts">

//import useAccessRight from "@/hooks/useAccessRight";
//const { hasAccess } = useAccessRight();
//import eventBus from "@/utils/eventBus";


import { ref, computed, watch, h, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";

// import iconSuccess from "@/assets/img/svg/icon-success.svg";

import iconSuccess from "@/assets/imgs/success_ico.png";
import iconWarning from "@/assets/imgs/warning_icon.png";

import NormalDialog from "@/components/NormalDialog.vue";
import { getAccountList, EditAccount, EnableAccount, addAccount, getUserInfo } from "@/apis/account";
import { getListByCreate, GetAccessRight } from "@/apis/accessGroup";
import { checkEmail, checkPhone } from "@/util/util";
import { ElMessage, ElMessageBox } from "element-plus";
import { successTips, warningTips, errorTips } from '@/utils/utils'
import useCountry from "@/hooks/useCountry";
const { getCountryCodeList, getCountryCodeListFetch } = useCountry();

import eventBus from "@/utils/eventBus";

import { useTreeBuilder } from "@/hooks/useTreeBuilder";
const { treeData, buildTree } = useTreeBuilder();


const props = defineProps<{
    updateAccountVisible: boolean;
    userId: number;
    updateQuery: () => void;
}>();

const emit = defineEmits<{
    (e: "update:updateAccountVisible", value: boolean): void;
    (e: "updateQuery"): void;
    (e: "updateSuccess"): void;
}>();

// 定义本地的 ref 来控制 el-dialog 的可见性
const dialogVisible = ref(false);

// 监听 props.updateAccountVisible 的变化，更新本地 ref
watch(() => props.updateAccountVisible, (newVal) => {
    dialogVisible.value = newVal;
}, { immediate: true });

// 监听本地 ref 的变化，通过 emit 通知父组件更新
watch(dialogVisible, (newVal) => {
    emit('update:updateAccountVisible', newVal);
});

// 获取用户信息
const userInfo = JSON.parse(localStorage.getItem("sign_admin_userInfo") || "{}");
const isSuperAdmin = computed(() => userInfo.userRoleType === 1);



const loading = ref(false);
const disableAccountVisible = ref(false);
const enableAccountVisible = ref(false);
const roleList = ref<any>();
const addFormRef = ref();


//判断当前权限参数
const UserRole = computed(() => {
    return isSuperAdmin.value;
});


const form = ref({
    UserRoleType: UserRole.value ? 1 : 2, // 根据权限决定默认角色
    UserAccount: "",
    UserName: "",
    AccessGroupId: UserRole.value ? 1 : null, // 超级管理员默认选1，分级管理员不设默认值
    RequireTFA: true,
    PhoneNo: "",
    AreaCode: "86",
    Email: "",
    userId: null,
    parentGroup: "",
});


const rules = ref({
    UserAccount: [
        {
            required: true,
            trigger: "blur",
            message: '请选择一个账号',
        },
        {
            pattern: /^[A-Z0-9]{8}$/,
            trigger: ["blur", "change"],
            message: "账号只允许输入数字或大写字母,长度为8位",
        },
    ],
    UserRoleType: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: '请选择身份',
        },
    ],
    UserName: [
        { required: true, trigger: "blur", message: "请输入名称" },
        {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
            message: "格式错误，仅支持中英文、数字、最长20个字符",
            trigger: "blur",
        },
    ],
    AccessGroupId: [
        { required: true, trigger: ["blur", "change"], message: "请选择权限组" },
    ],
    PhoneNo: [
        { required: true, trigger: "blur", message: "请输入电话号码" },
        { validator: checkPhone, trigger: "blur" },
    ],
    RequireTFA: [
        { required: true, trigger: ["blur", "change"], message: "请选择是否二次认证" },
    ],
    Email: [
        {
            validator: checkEmail,
            trigger: ["blur", "change"],
            required: true,
            message: "请输入邮箱",
        },
    ],
})



//对话框关闭时重置表单状态
const handleDialogClosed = () => {
    form.value = {
        UserRoleType: UserRole.value ? 1 : 2, // 根据权限决定默认角色
        UserAccount: "",
        UserName: "",
        AccessGroupId: UserRole.value ? 1 : null, // 超级管理员默认选1，分级管理员不设默认值
        RequireTFA: true,
        PhoneNo: "",
        AreaCode: "86",
        Email: "",
        userId: null,
        parentGroup: "",
    }
}


//节点点击事件
const handleNodeClick = (data: any) => {
    form.value.AccessGroupId = data.value;
};


//角色切换按钮事件
const handleRoleChange = (value: number) => {
    if (value === 1) {
        form.value.AccessGroupId = 1;
    } else {
        form.value.AccessGroupId = null;
    }
};


//回显当前用户数据
const feedbackUser = () => {
    // 确保 userId 存在且弹窗可见才进行数据回显
    if (props.userId && props.updateAccountVisible) {
        getForSelect(); // 确保权限组数据已加载
        getUserInfo({ userId: props.userId }).then(res => {
            if (res.code === 1 && res.data) {
                form.value.userId = props.userId;
                form.value.UserAccount = res.data.loginAccount;
                form.value.UserName = res.data.userName;
                form.value.UserRoleType = res.data.userRoleType;
                form.value.PhoneNo = res.data.phoneNo;
                form.value.AreaCode = res.data.areaCode;
                form.value.Email = res.data.email;
                form.value.RequireTFA = res.data.requireTFA;
                // 延迟设置 AccessGroupId，避免被 UserRoleType 的 watch 清空
                setTimeout(() => {
                    form.value.AccessGroupId = res.data.accessGroupId;
                }, 100);
            }
        }).catch(error => {
            errorTips('获取用户详情失败');
        });
    } else {
        // 如果没有 userId 或者弹窗不可见，重置表单
        handleDialogClosed();
    }
};


// 监听弹窗显示状态和 userId，当打开时重新加载数据
watch(
    () => [props.updateAccountVisible, props.userId],
    ([newVisible, newUserId]) => {
        if (newVisible) {
            if (newUserId) {
                // 编辑模式：加载用户数据
                feedbackUser();
            } else {
                // 新增模式：重置表单
                handleDialogClosed();
            }
        } else {
            // 弹窗关闭时重置表单
            handleDialogClosed();
        }
    },
    { immediate: true }
);



//账号弹窗保存事件
const save = () => {
    // 如果是分级管理员但未选择权限组，给出提示并返回
    if (form.value.UserRoleType === 2 && !form.value.AccessGroupId) {
        warningTips('请选择权限组')
        return;
    }

    // 如果是编辑，需要传入 userId
    if (form.value.userId) {
        addFormRef.value.validate((valid: boolean) => {
            if (valid) {
                if (!form.value.AreaCode) {

                    warningTips('请选择一个地区码')
                    return;
                }
                loading.value = true;

                //编辑的逻辑
                EditAccount({
                    userId: form.value.userId,
                    UserName: form.value.UserName,
                    AccessGroupId: form.value.AccessGroupId || 1,
                    UserAccount: form.value.UserAccount,
                    PhoneNo: form.value.PhoneNo,
                    AreaCode: form.value.AreaCode,
                    RequireTFA: form.value.RequireTFA,
                    Email: form.value.Email,
                    UserRoleType: form.value.UserRoleType,
                })
                    .then((res) => {
                        if (res.code === 1) {
                            successTips('编辑成功')
                            loading.value = false;
                            emit("updateQuery");
                            emit("update:updateAccountVisible", false);
                        } else if (res.code === 19) {
                            loading.value = false;
                        } else if (res.code === 15) {

                            loading.value = false;
                        } else if (res.code === 622) {
                            loading.value = false
                        } else if (res.code === 2) {
                            loading.value = false
                        }

                        // 如果编辑的是当前登录用户，更新sessionStorage中的信息
                        const meInfo = JSON.parse(localStorage.getItem("sign_admin_userInfo") || "{}");
                        if (meInfo.userId === form.value.userId) {
                            meInfo.nickName = form.value.UserName;
                            localStorage.setItem("sign_admin_userInfo", JSON.stringify(meInfo));
                            // 触发事件总线事件，通知其他组件更新用户信息
                            eventBus.emit("updateUserInfo");
                        }
                    })
            }
        });
    } else {

        addFormRef.value.validate((valid: boolean) => {
            if (valid) {
                if (!form.value.AreaCode) {
                    warningTips('请选择一个地区码')
                    return;
                }
                // 新增模式
                if (form.value.UserRoleType === 1) {
                    form.value.AccessGroupId = 1;
                }

                const addForm = {
                    UserAccount: form.value.UserAccount,
                    UserName: form.value.UserName,
                    AccessGroupId: form.value.AccessGroupId || 1, // 如果未选择权限组，默认使用ID为1的权限组
                    UserRoleType: form.value.UserRoleType,
                    PhoneNo: form.value.PhoneNo,
                    AreaCode: form.value.AreaCode,
                    RequireTFA: form.value.RequireTFA,
                    Email: form.value.Email,
                };
                loading.value = true;
                //新增的逻辑
                addAccount(addForm)
                    .then((res) => {
                        if (res.code === 1) {
                            ElMessageBox.alert(
                                '创建成功，账号的初始登录密码为：' + res.data.password, {
                                confirmButtonText: '确认',
                                dangerouslyUseHTMLString: true,
                                customClass: "publish-messagebox",
                                icon: h("img", {
                                    class: "warning-icon",
                                    src: iconSuccess,
                                    style: {
                                        width: '20px',
                                        height: '20px',
                                        marginRight: '5px'
                                    }
                                }),
                            });
                            loading.value = false;
                            emit("updateQuery");
                            emit("update:updateAccountVisible", false);
                        } else if (res.code === 19) {
                            loading.value = false;
                        } else if (res.code === 15) {

                            loading.value = false;
                        } else if (res.code === 622) {
                            loading.value = false
                        } else if (res.code === 2) {
                            loading.value = false
                        }
                    })

            }
        });
    }
};





//弹窗返回事件
const goReturn = () => {
    // 清空表单验证状态
    addFormRef.value.clearValidate();
    handleDialogClosed();
    emit("update:updateAccountVisible", false);
};


//二次验证弹窗关闭事件
const closeDisableDialog = (val: boolean) => {
    disableAccountVisible.value = val;
    enableAccountVisible.value = val;
};


//二次验证TFA
const enableAccount = () => {
    enableAccountVisible.value = false;
    EnableAccount({
        userId: form.value.userId,
        isActive: false,

    })
        .then((res) => {
            if (res.code === 1) {
                successTips('操作成功')
            }
        });
};

//封禁账号
const disableAccount = () => {
    disableAccountVisible.value = false;
    EnableAccount({
        userId: form.value.userId,
        isActive: true,

    })
        .then((res) => {
            if (res.code === 1) {
                successTips('操作成功')
            }
        });
};








// 获取树形数据
const getForSelect = () => {
    return new Promise<void>((resolve) => {
        getListByCreate().then((res) => {
            if (!res.data || res.data.length === 0) {
                resolve();
                return;
            }
            const formattedData = res.data.map((item: any) => {
                return {
                    accessGroupId: item.accessGroupId,
                    label: item.groupName,
                    value: item.accessGroupId,
                    userType: item.userType,
                    parentGroupId: item.parentGroupId,
                    description: item.description,
                };
            });

            // 过滤掉顶级节点
            const filteredData = formattedData.filter((item: any) => {
                return (
                    item.parentGroupId !== 0 &&
                    item.parentGroupId !== null &&
                    item.parentGroupId !== undefined
                );
            });

            // 构建树形结构
            buildTree(filteredData);
            resolve();
        });
    });
};


const init = () => {
    getListByCreate({
        isAll: 1,
    }).then((res) => {
        roleList.value = res.data;
    });
    getForSelect();
};



// 监听角色类型变化
watch(
    () => form.value.UserRoleType,
    (newVal) => {
        // 当选择超级管理员时，清空权限组值
        if (newVal === 1) {
            form.value.AccessGroupId = null;
        }
    }
);



getCountryCodeListFetch();
init();

onMounted(() => {
    getForSelect()
})






</script>

<style scoped lang="scss">
.common-input {
    width: 100%;
}

.detail {
    padding: 20px;
}

.money-select {
    width: 140px;
    height: 36px;
}

.el-dialog {
    :deep(.el-dialog__title) {
        font-size: 16px;
        font-weight: 800;
        color: #02011b;
    }
}

:deep(.el-select__wrapper) {
    background-color: #f4f4f9;
    // box-shadow: none;
}

:deep() {
    .el-input-group--prepend .el-input-group__prepend .el-select .el-select__wrapper {
        height: 100%;
    }
}

.editBottom {
    display: flex;
    justify-content: flex-end;
}

:deep(.publish-messagebox) {
    .el-message-box__status {
        display: flex;
        align-items: center;
    }

    .warning-icon {
        width: 20px;
        height: 20px;
        margin-right: 5px;
    }
}
</style>
